package com.cl.utility.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liddhappy
 * @className fileUtils
 * @description 文件工具类
 * @date 2022/6/8 10:30
 */
public class FileUtils {
    /**
     * 默认文件大小20M
     */
    public static long DEFAULT_MAX_SIZE = 20 * 1024 * 1024;

    public static final int DEFAULT_FILE_NAME_LENGTH = 100;
    public static final String CLASS_PATH = "classpath:";
    public static final String JSON_SUFFIX = ".json";
    private static final String XLSX_SUFFIX = ".xlsx";
    private static final String XLS_SUFFIX = ".xls";

    /**
     * 读取文件内容
     *
     * @param path 文件路径
     * @return 文件内容
     * @throws IOException
     */
    public static String readStrFromFile(String path) throws IOException {
        StringBuilder content = new StringBuilder();
        File file = new File(path);
        if (file.isFile() && file.exists()) {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String lineText = null;
            while ((lineText = bufferedReader.readLine()) != null) {
                content.append(lineText);
            }
            reader.close();
        } else {
            System.out.println("");
        }
        return content.toString();
    }

    /**
     * 写入数据到文件
     *
     * @param data 数据
     * @param path 文件路径
     * @return
     */
    public static boolean writeContentToFile(String data, String path) {
        File file = new File(path);
        if (file.exists()) {
            file.mkdirs();
        }
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            writer.write(data);
            writer.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件找不到");
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("没有写入数据");
            return false;
        }
        return true;
    }

    /**
     * 从MultipartFile文件中获取内容。
     *
     * @param file 文件
     * @return 文件内容
     * @throws IOException
     */
    public static String readStrFromMultipartFile(MultipartFile file) throws IOException {
        String Content = null;
        InputStream is = file.getInputStream();
        InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(reader);
        while (br.ready()) {
            Content += br.readLine();
        }
        return file.isEmpty() ? null : Content;
    }

    /**
     * 遍历文件夹
     *
     * @param folder 文件
     * @return 文件集合
     */
    public static List<File> folderTraversal(File folder) {
        List<File> files = new ArrayList<>();
        File[] listFiles = folder.listFiles();
        if (listFiles.length != 0) {
            for (File file : listFiles) {
                if (file.isFile()) {
                    files.add(file);
                } else {
                    folderTraversal(file);
                }
            }
        }
        return files;
    }

    public static String getClassPath() throws FileNotFoundException {
        File file = new File(ResourceUtils.getURL(CLASS_PATH).getPath());
        return file.getAbsolutePath();
    }

    /**
     * 读取resource 路径下 json文件
     *
     * @param fileFolder 文件夹名称
     * @param fileName   文件名
     * @return
     * @throws IOException
     */
    public static String getResourceJsonFileContent(String fileFolder, String fileName) throws Exception {
        if ((StringUtils.isNoneBlank(fileName) && StringUtils.isNoneBlank(fileFolder))) {
            return fileName.contains(JSON_SUFFIX)
                    ? getResourceFile(fileFolder, fileName) : getResourceFile(fileFolder, fileName + JSON_SUFFIX);
        }
        return "any of fileFolder or fileName have empty value";
    }

    /**
     * 获取resource 路径下的excel 表格
     *
     * @param fileFolder 文件夹路径
     * @param fileName   文件名
     * @return
     * @throws Exception
     */
    public static String getResourceExcelFileContent(String fileFolder, String fileName) throws Exception {
        if ((StringUtils.isNoneBlank(fileName) && StringUtils.isNoneBlank(fileFolder))) {
            String result = null;
            if (fileName.contains(XLS_SUFFIX) || fileName.contains(XLSX_SUFFIX)) {
                result = getResourceFile(fileFolder, fileName);
            } else {
                result = getResourceFile(fileFolder, fileName + XLSX_SUFFIX);
            }
            return result;
        }
        return "any of fileFolder or fileName have empty value";
    }

    /**
     * 读取resource文件夹中文件
     *
     * @param fileFolder 文件夹
     * @param fileName   文件名带后缀
     * @return
     * @throws IOException
     */
    public static String getResourceFile(String fileFolder, String fileName) throws Exception {
        String template = "%s\\%s\\%s";
        String fileRelation = String.format(template, getClassPath(), fileFolder, fileName);
        String fileSuffix = "." + fileName.substring(fileName.lastIndexOf('.') + 1);
        String result = null;
        switch (fileSuffix) {
            case JSON_SUFFIX:
                result = readStrFromFile(fileRelation);
                break;
            case XLSX_SUFFIX:
                File excelFile = new File(fileRelation);
                result = ExcelUtils.readFile(excelFile).toJSONString();
                break;
            case XLS_SUFFIX:
                File excelFile2 = new File(fileRelation);
                result = ExcelUtils.readFile(excelFile2).toJSONString();
                break;
            default:
                break;
        }
        return result;
    }
}
